package server

import (
	"context"
	"github.com/go-kratos/kratos/v2/log"
	"github.com/go-kratos/kratos/v2/middleware/logging"
	"github.com/go-kratos/kratos/v2/middleware/recovery"
	"github.com/go-kratos/kratos/v2/middleware/selector"
	"github.com/go-kratos/kratos/v2/middleware/tracing"
	"github.com/go-kratos/kratos/v2/middleware/validate"
	"github.com/go-kratos/kratos/v2/transport/http"
	"github.com/go-kratos/swagger-api/openapiv2"
	adminMenuApi "go-skeleton/api/admin/service/admin_menu"
	adminRoleApi "go-skeleton/api/admin/service/admin_role"
	adminUserApi "go-skeleton/api/admin/service/admin_user"
	langApi "go-skeleton/api/admin/service/lang"
	"go-skeleton/app/admin/service/internal/conf"
	"go-skeleton/app/admin/service/internal/service/admin_menu"
	"go-skeleton/app/admin/service/internal/service/admin_role"
	"go-skeleton/app/admin/service/internal/service/admin_user"
	"go-skeleton/app/admin/service/internal/service/lang"
	"go-skeleton/pkg/middleware/jwt"
	tracesdk "go.opentelemetry.io/otel/sdk/trace"
)

func NewWhiteListMatcher() selector.MatchFunc {

	whiteList := make(map[string]struct{})
	whiteList["/admin.AdminUserService/Captcha"] = struct{}{}
	whiteList["/admin.AdminUserService/Login"] = struct{}{}
	whiteList["/admin.AdminUserService/SendCode"] = struct{}{}
	whiteList["/admin.LangService/GetLang"] = struct{}{}
	return func(ctx context.Context, operation string) bool {
		if _, ok := whiteList[operation]; ok {
			return false
		}
		return true
	}
}

// NewHTTPServer new an HTTP server.
func NewHTTPServer(c *conf.Server, ca *conf.Auth, logger log.Logger, tp *tracesdk.TracerProvider,
	adminUser *admin_user.AdminUserService,
	menu *admin_menu.MenuService,
	role *admin_role.RoleService,
	lang *lang.LangService,
) *http.Server {
	var opts = []http.ServerOption{
		http.Middleware(
			recovery.Recovery(),
			tracing.Server(
				tracing.WithTracerProvider(tp)),
			logging.Server(logger),
			validate.Validator(),
			selector.Server(jwt.NewAuthServer(ca.AdminKey)).Match(NewWhiteListMatcher()).Build(),
			// casbin
		),
	}
	if c.Http.Network != "" {
		opts = append(opts, http.Network(c.Http.Network))
	}
	if c.Http.Addr != "" {
		opts = append(opts, http.Address(c.Http.Addr))
	}
	if c.Http.Timeout != nil {
		opts = append(opts, http.Timeout(c.Http.Timeout.AsDuration()))
	}
	srv := http.NewServer(opts...)
	h := openapiv2.NewHandler()
	srv.HandlePrefix("/q/", h)
	adminUserApi.RegisterAdminUserServiceHTTPServer(srv, adminUser)
	adminMenuApi.RegisterMenuServiceHTTPServer(srv, menu)
	adminRoleApi.RegisterRoleServiceHTTPServer(srv, role)
	langApi.RegisterLangServiceHTTPServer(srv, lang)
	return srv
}
